package com.example.datastorgedemo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void innerWrite(View view) throws Exception {
        FileOutputStream fos = openFileOutput("inner.txt",MODE_PRIVATE);
        fos.write("Hello, Inner Storge".getBytes());
        fos.close();
        Toast.makeText(this, "写入数据成功", Toast.LENGTH_SHORT).show();
    }

    public void innerRead(View view) throws Exception {
        FileInputStream fis = openFileInput("inner.txt");
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        Toast.makeText(this, new String(buffer), Toast.LENGTH_SHORT).show();
    }

    public void outerWrite(View view) throws Exception {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)){
//            写入数据
            File path = Environment.getExternalStorageDirectory();
            File file = new File(path, "outer.txt");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write("Hello,Outer storge!".getBytes());
            fos.close();
            Toast.makeText(this, "写入外部文件成功", Toast.LENGTH_SHORT).show();
        }
    }

    public void outerRead(View view) throws Exception {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)){
            File path = Environment.getExternalStorageDirectory();
            File file = new File(path, "outer.txt");
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            Toast.makeText(this, new String(bytes), Toast.LENGTH_SHORT).show();
            fis.close();
        }
    }

    public void spWrite(View view){
            getSharedPreferences("data", MODE_PRIVATE).edit()
                    .putInt("age",18)
                    .putString("name","Hello,zhangsan").apply();
            Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
    }
    public void spRead(View view){
            SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
            int age = sp.getInt("age",0);
            String name = sp.getString("name","");
            Toast.makeText(this, "age:"+age+",name"+name, Toast.LENGTH_SHORT).show();
    }

    public void toSqlite(View view) {
        Intent intent = new Intent(this, SqliteActivity.class);
        startActivity(intent);
    }
}